package com.merry.api.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.merry.api.validator.ApiValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * 做第三方验证的filter
 */
@Component
public class ApiFilter extends OncePerRequestFilter {

    @Autowired
    private List<ApiValidator> apiValidatorList;

    @Value("${skipUrl}")
    private List<String> skipUrl;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            //当前请求的url
            String url = request.getServletPath();
            //需要跳过的url。
            if(skipUrl.contains(url)){
                filterChain.doFilter(request,response);
                return;
            }
            //执行后续的验证逻辑。
            for (ApiValidator a : apiValidatorList) {
                if (!a.verify(request)) {
                    //向前端写错误信息。
                    writeError(response, "500", "验证错误！");
                    return;
                }
            }
        } catch (Exception e) {
            writeError(response, "401", e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 往前端写错误信息
     *
     * @param response 响应
     * @param code     响应码
     * @param msg      出错信息
     * @throws IOException IO异常
     */
    private void writeError(HttpServletResponse response, String code, String msg) throws IOException {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(code,msg);
        response.getWriter().write(JSONUtils.toJSONString(hashMap));
    }

}
